<template>
  <div class="mt-verify-btn {{locked ? 'locked' : ''}}">
    <button class="mt-verify-button"
            form-type="button" @tap="bindClick">
      <block v-if="locked">
        <text><slot name="before"></slot></text>
        <text>{{time}}</text>
        <text><slot name="append"></slot></text>
      </block>
      <block v-else><slot></slot></block>
    </button>
  </div>
</template>

<script>
  let interval

  function startCountDownTask(cb, ifclear, end) {
    interval = setInterval(function () {
      let needStop = ifclear()
      if (!needStop) {
        cb()
      } else {
        clearInterval(interval)
        setTimeout(function () {
          end()
        }, 0)
      }
    }, 1000)
  }

  export default {
    behaviors: [],
    properties: {
      max: {
        type: Number,
        value: 60
      },
      append: String,
      before: String,
      auto: {
        type: Boolean,
        value: true
      },
      action: Number,
      mobile: String,
    },
    data() {
      return {
        num: 0,
        locked: false,
        time: -1
      }
    },
    methods: {
      runTask() {
        let self = this
        let num = self.data.num + 1
        self.setData({
          num:  num,
          time: self.data.max - num
        })
      },
      stopTask() {
        let self = this
        clearInterval(interval)
        self.setData({
          locked: false,
          num: 0
        })
      },
      run() {
        let self = this
        if (!this.data.locked) {
          self.setData({
            locked: true
          })
          wx.request({
            method: 'POST',
            url: `${$global.config.request.base}/user/validate/`,
            data: {
              mobile: this.data.mobile,
              action: this.data.action,
            },
            success(e) {
              if (e && e.data && e.data.code === 20000) {

              } else {
                app.showToast('短信发送失败')
              }
            },
            fail(e) {
              app.showToast('短信发送失败')
            }
          })
          self.runTask()
          startCountDownTask(function () {
            self.runTask()
          }, function () {
            return self.data.num > self.data.max - 2
          }, function () {
            self.setData({
              locked: false,
              num: 0
            })
          })
        }
      }
    },
    handles: {
      bindClick(e) {
        if (this.data.auto) {
          this.run()
        }
      },
    }
  }
</script>

<style lang="less">
</style>
